import React, { useState, useEffect } from 'react'
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { makeStyles, useTheme } from '@material-ui/core/styles';
import { useSelector, useDispatch } from 'react-redux'
import { Grid, Typography } from '@material-ui/core';
import { Image, Icon } from 'components/atoms';
import { callGetNewsApi, callPostNewsApi } from 'utils/networking';
import { setDisCovers } from 'redux/actions/CoverActions';
import { useHistory } from "react-router-dom";

const useStyles = makeStyles(theme => ({
    root: {
        width: "100%",
        padding: "30px 20px 100px",
        background: "#000",
        position: "relative",
        [theme.breakpoints.up('md')]: {
            padding: "30px 20px 100px",
        },
    },
    profileTitle: {
        fontSize: "28px",
        fontWeight: "bold",
        flex: '0 0 auto',
        whiteSpace: 'nowrap',
        color: "#fff",
        marginBottom: "20px",
        [theme.breakpoints.up('md')]: {
            fontSize: "38px",
        },

    },
    profileBrief: {
        color: "#fff",
        fontSize: "18px",
        width: "100%",
        marginBottom: "10px",
        [theme.breakpoints.up('md')]: {
            fontSize: "22px",
        },
    },
    grid: {
        borderBottom: "5px solid #fff",
        paddingBottom: "20px",
        marginBottom: "20px",
    },
    topPlayed: {
        marginTop: "30px"
    },
    topPlayedImage: {
        height: "80px",
        width: "80px",
        borderRadius: "6px",
        overflow: "hidden",
        [theme.breakpoints.up('md')]: {
            width: "100px",
            height: "100px",
        },
    },
    img: {
        objectFit: "cover",
        verticalAlign: "middle",
    },
    topPlayedGrid: {
        margin: "10px 0 10px",
        padding: "10px",
        flexWrap: "nowrap",
        cursor: "pointer",
        background: "#fff",
        borderRadius: "6px",
    },
    topPlayedGridItem: {
        marginLeft: "10px",
        width: "100%",
        [theme.breakpoints.up('lg')]: {
            marginLeft: "20px",
        },
    },
    iconButton: {
        position: "relative",
    },
    topPlayedText: {
        overflow: "hidden",
        textOverflow: "ellipsis",
        whiteSpace: "nowrap",
        width: "90%",
        fontSize: "18px",
        [theme.breakpoints.up('md')]: {
            fontSize: "32px",
        },
    },
    text: {
        color: "#92929D",
        fontSize: "16px",
        [theme.breakpoints.up('md')]: {
            fontSize: "20px",
        },
    },
    ul: {
        position: "absolute",
        top: "100%",
        right: "0",
        listStyle: "none",
        zIndex: 20,
        borderRadius: "0 0 4px 4px",
        overflow: "hidden",
        borderTop: "1px solid rgba(0, 0, 0, 0.10)",
        backgroundColor: "#FFFFFF",
    },
    ulHead: {
        display: "flex",
        justifyContent: "space-between",
        alignItems: "center",
        padding: "10px 20px",
        fontFamily: "HurmeGeometricSans3-Black",
        borderBottom: "1px solid rgba(0, 0, 0, 0.10)",
    },
    ulFoot: {
        display: "flex",
        justifyContent: "start",
        alignItems: "center",
        padding: "10px 30px 20px",
        fontFamily: "HurmeGeometricSans3-Black",
        borderTop: "1px solid rgba(0, 0, 0, 0.10)",
    },
    content: {
        maxHeight: "200px",
        overflowY: "auto",
        overflowX: "hidden",
    },
    li: {
        width: "150px",
        cursor: "pointer",
        padding: "8px 40px",
        "&:hover": {
            backgroundColor: "#EDF5FA",
        },
        fontSize: "14px",
        display: "flex",
        justifyContent: "start",
        alignItems: "center",
        minHeight: "50px",
        [theme.breakpoints.up('md')]: {
            width: "250px",
        },
    },
    i: {
        "& svg": {
            verticalAlign: "middle"
        }
    },
    mark: {
        position: "absolute",
        width: "100%",
        height: "100%",
        zIndex: 10,
        marginTop: "-64px",
    },
}));

function MyTop(props) {
    const { data, className, ...rest } = props;
    const classes = useStyles();
    const dispatch = useDispatch();
    const history = useHistory();
    const profileData = useSelector((state) => state.auth.profileData)

    const [playlists, setPlaylists] = useState([]);
    const [topSongs, setTopSongs] = useState([]);
    const [choosePlaylist, setChosePlaylist] = useState(null);

    useEffect(() => {
        getServerSideProps();
    }, [])

    const getServerSideProps = async () => {
        callGetNewsApi('cover/discovers', dispatch, (data) => {
            dispatch(setDisCovers(data));
        });
        callGetNewsApi('song/my_top_songs', dispatch, (data) => {
            console.log(data)
            setTopSongs(data)
        });
    }

    const handleCount = (count) => {
        let int = count > 1000 ? (parseInt(count / 1000) + "K") : count
        return int
    }

    const handleShowPlaylists = (e, index) => {
        e.stopPropagation()
        setChosePlaylist(index)
        if (!playlists.length) {
            getServerPlaylistsProps()
        }
    };

    const getServerPlaylistsProps = async () => {
        if (!profileData || !profileData.id) {
            history.push(`signin`);
            return;
        }
        callGetNewsApi(`song/user_playlists?user_id=${profileData.id}&all=1`, dispatch, (data) => {
            console.log(data);
            setPlaylists(data);
        })
    }

    const handleAddPlaylists = (e, name, id) => {
        e.stopPropagation()
        callPostNewsApi('song/playlist_songs_cloud_add', { user_id: profileData.id, playlist: name, song_ids: id }, dispatch, (data) => {
            // console.log(data);
            setChosePlaylist(null)
        })
    };

    const handleMarkClose = () => {
        setChosePlaylist(null)
    };

    return (
        <div className={clsx(classes.root)} >
            <div className={classes.mark} style={{ height: choosePlaylist !== null ? "100%" : "0" }} onClick={handleMarkClose}></div>
            <div>
                <Typography variant="body2" color="textPrimary" className={clsx(classes.profileTitle)}>
                    My Top 10
                </Typography>

                {topSongs.map((item, index) => (<Grid container className={classes.topPlayedGrid} key={index} onClick={() => {
                    window.location.href = `${process.env.REACT_APP_SERVER_URL}player/album/${item.id}`;
                }}>
                    <Grid item>
                        <div className={classes.topPlayedImage}>
                            <Image
                                src={item.album_art}
                                alt={item.album_art}
                                srcSet={item.album_art}
                                lazyProps={{ width: '100%', height: '100%' }}
                                className={classes.img}
                            />
                        </div>
                    </Grid>
                    <Grid item xs={4} md={5} lg={6} className={classes.topPlayedGridItem} container direction="column" justifyContent="center">
                        <Typography className={clsx(classes.profileTitle, classes.topPlayedText)} style={{ color: "#000" }}>{item.albumName}</Typography>
                        <Typography className={clsx(classes.profileText)} style={{ color: "#5541D7" }}>{item.artistName}</Typography>
                    </Grid>

                    <Grid item xs={1} sm={2} className={classes.topPlayedGridItem} container direction="column" justifyContent="center">
                        <Typography className={clsx(classes.text)}>{handleCount(item.plays)}</Typography>
                    </Grid>

                    <Grid item xs={2} className={classes.topPlayedGridItem} container direction="column" justifyContent="center">
                        <Typography className={clsx(classes.text)}>{item.artistName}</Typography>
                    </Grid>

                    <Grid item xs={2} md={1} className={clsx(classes.topPlayedGridItem, classes.iconButton)} container justifyContent="center" alignItems='center' onClick={(e) => {
                        e.stopPropagation()
                    }}>
                        <Icon
                            fontIconClass="fas fa-share-alt"
                            style={{ color: "#92929D" }}
                        />
                        <Icon
                            fontIconClass="fas fa-plus"
                            style={{ color: "#92929D", margin: "0 10px", zIndex: 19 }}
                            onClick={(e) => handleShowPlaylists(e, index)}
                        />
                        <ul className={clsx(classes.ul)} style={{ display: choosePlaylist == index ? "block" : "none" }}>
                            <div className={classes.ulHead}>Choose Playlist
                                <Icon
                                    fontIconClass="fa fa-times"
                                    size="small"
                                    style={{ opacity: 0.5, cursor: "pointer" }}
                                    onClick={() => setChosePlaylist(null)}
                                />
                            </div>
                            <div className={classes.content}>
                                {
                                    playlists.map((ele, i) => <li className={clsx(classes.li)} onClick={(e) => handleAddPlaylists(e, ele.name, item.id)} key={i}>
                                        {ele.name}
                                    </li>)
                                }
                            </div>
                        </ul>
                    </Grid>

                </Grid>))}
            </div>
        </div>
    )
}

MyTop.propTypes = {
    /**
     * External classes
     */
    className: PropTypes.string,
};

export default MyTop

